﻿using Avalonia.Controls;
using Avalonia.Controls.Shapes;
using Avalonia.Markup.Xaml;
using Avalonia.Metadata;
using Avalonia.Threading;
using ScottPlot;
using ScottPlot.Avalonia;
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using P2P.CrossPlatform;

namespace P2P.Client.UI.Features.Statistics;
 
public partial class StatisticsView : UserControl
{
    private AvaPlot _cpuPlot { get; set; }
    private AvaPlot _memoryPlot { get; set; }

    public StatisticsView()
    {
        InitializeComponent();

        _cpuPlot = this.Find<AvaPlot>("CPUPlot");

        _cpuPlot?.Plot.XLabel("Time (ms)");
        _cpuPlot?.Plot.YLabel("CPU Usage (%)");
        _cpuPlot?.Plot.Axes.SetLimitsX(60, 0);
        _cpuPlot?.Plot.Axes.SetLimitsY(0, 100);
        _memoryPlot = this.Find<AvaPlot>("MemoryPlot");

        _memoryPlot?.Plot.XLabel("Time (ms)");
        _memoryPlot?.Plot.YLabel("Memory Usage (MB)");
        _memoryPlot?.Plot.Axes.SetLimitsX(60, 0);

        ProcessMonitor.Instance.StartMonitor(async (result) => 
        {
            //// 更新图表
            await Dispatcher.UIThread.InvokeAsync(() =>
            {
                _cpuPlot?.Plot.Title($"CPU Usage: {result.CurrentCpuUsage}%");
                _cpuPlot?.Plot.Add.Signal(result.CpuUsageHistory);

                _memoryPlot?.Plot.Title($"Memory Usage: {result.CurrentMemoryUsageMB}MB({result.CurrentMemoryUsageGB}GB), Total Memory: {result.TotalMemoryGB}GB");
                _memoryPlot?.Plot.Add.Signal(result.MemoryUsageHistory);
                _cpuPlot?.Refresh();
                _memoryPlot?.Refresh();
            });
        }) ;
    }

    private void InitializeComponent()
    {
        AvaloniaXamlLoader.Load(this);
    }
}